import { type ChangeEvent, type KeyboardEventHandler, useEffect } from 'react'
import { debounce } from 'lodash-es'
import { useSettingStore, useSnippetsStore, useSuggestionStore } from '@renderer/stores'
import { getAbbreviation, template } from '@renderer/utils'
import { useSearchSnippets } from '../useSearchSnippets'
import { useSearchDefault } from '../useSearchDefault'
import { useIpaddress } from '../useIpaddress'
import { useDateTime } from '../useDateTime'
import { useUuid } from '../useUuid'
import { useSearchBrowser } from '../useSearchBrowser'
import { useSearchBookmarks } from '../useSearchBookmarks'
import { useTranslate } from '../useTranslate'
import { useSearchApps } from '../useSearchApps'

export function useSearch () {
  const value = useSnippetsStore(state => state.searchValue)
  const systemSearchItems = useSettingStore(s => s.systemSearchItems)
  const browserSearchItems = useSettingStore(s => s.browserSearchItems)
  const setSearchValue = useSnippetsStore(state => state.setSearchValue)
  const setSnippets = useSnippetsStore(state => state.setSnippets)
  const setShowSuggestion = useSuggestionStore(s => s.setShowSuggestion)
  const { searchSnippets } = useSearchSnippets()
  const { searchDefault } = useSearchDefault()
  const { searchBookmarks } = useSearchBookmarks()
  const { getIpaddress } = useIpaddress()
  const { getDateTime } = useDateTime()
  const { searchInBrowser } = useSearchBrowser()
  const { getUuid } = useUuid()
  const { translate: t } = useTranslate()
  const translate = debounce(t, 200)
  const { searchApps } = useSearchApps()

  const handleChange = async (e: ChangeEvent<HTMLInputElement>) => {
    setSearchValue(e.target.value)
  }
  const handleKeydown: KeyboardEventHandler<HTMLInputElement> = (e) => {
    if (['ArrowDown', 'ArrowUp'].includes(e.code)) {
      e.preventDefault()
    }
  }

  useEffect(() => {
    setShowSuggestion(!value)
    
    const keyword = value.replace(/^\s+/g, '')
    if (!keyword) {
      return setSnippets([])
    }

    const abbr = getAbbreviation(keyword)
    const currentItem = [
      ...systemSearchItems,
      ...browserSearchItems,
    ].find(i => {
      return i.abbreviation === abbr?.toLowerCase()
    })
    switch (currentItem?.type) {
      case 'ip':
        getIpaddress()
        break
      case 'datetime':
        getDateTime(keyword.replace(abbr!, '').trim())
        break
      case 'snippets':
        searchSnippets(keyword.toLowerCase())
        break
      case 'bookmarks':
        searchBookmarks(keyword.replace(abbr!, '').trim().toLowerCase())
        break
      case 'uuid':
        getUuid()
        break
      case 'translate':
        translate(keyword.replace(abbr!, '').trim())
        break;
      case 'apps':
        searchApps(keyword.replace(abbr!, '').trim().toLowerCase())
        break
      case undefined:
        // 默认为搜索文本片段
        searchDefault(keyword.toLowerCase())
        break
      default:
        // 浏览器搜索
        if (currentItem && 'url' in currentItem) {
          searchInBrowser(
            `${currentItem.name}搜索`,
            template.render(
              currentItem.url, encodeURIComponent(keyword.replace(abbr!, '').trim())),
            currentItem.icon,
          )
        }
    }
  }, [value])

  return {
    value,
    handleChange,
    handleKeydown,
  }
}
